package com.yinxing.framework.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.*;

/**
 * 阿里云OSS文件上传工具类
 */
public class OSSUtils {

    private OSS ossClient = null;

    @Value("${yinxing.config.oss.accessKeyId}")
    private String accessKeyId ;
    @Value("${yinxing.config.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${yinxing.config.oss.endpoint}")
    private String endpoint;
    @Value("${yinxing.config.oss.bucketName}")
    private String bucketName;

    @PostConstruct
    public void init() {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    @PreDestroy
    public void destroy() {
        ossClient.shutdown();
    }

    /**
     * 上传文件
     * @param file MultipartFile对象
     * @return 返回文件URL
     * @throws IOException
     */
    public String putMultipartFile(MultipartFile file) throws IOException {
        String fileURL = null;
        if(file != null && !file.isEmpty()) {
            fileURL = this.putObject(file.getInputStream(),
                    FileUtils.getSequenceFileName(file.getOriginalFilename()),
                    file.getContentType());
        }
        return fileURL;
    }

    /**
     * 上传文件到OSS
     * @param input 输入流
     * @param fileName 文件名:如UUID.txt 名称不能重复,所以在提交时尽量不要用原始文件名
     * @param contentType 文件类型
     * @return 文件访问URL
     */
    public String putObject(InputStream input, String fileName, String contentType) {
        ObjectMetadata meta = new ObjectMetadata();
        meta.setObjectAcl(CannedAccessControlList.Default);
        meta.setContentType(contentType);
        meta.setCacheControl("no-cache");
        PutObjectRequest request = new PutObjectRequest(bucketName, fileName, input, meta);
        ossClient.putObject(request);
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }

    /**
     * 删除文件
     * @param fileName 文件名称
     */
    public void deleteObject(String fileName) {
        GenericRequest request = new DeleteObjectsRequest(bucketName).withKey(fileName);
        ossClient.deleteObject(request);
    }

    /**
     * 返回文件二进制数组
     * @param fileName 文件名称
     */
    public byte[] getObject(String fileName) {
        GetObjectRequest request = new GetObjectRequest(bucketName, fileName);
        OSSObject result = ossClient.getObject(request);
        try {
            return IOUtils.readStreamAsByteArray(result.getObjectContent());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}